/*
 * Copyright (c) 2012 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.libermundi.theorcs.core.tapestry.services.assets;

import java.io.IOException;

import javax.servlet.http.HttpServletResponse;

import org.apache.tapestry5.SymbolConstants;
import org.apache.tapestry5.ioc.annotations.InjectService;
import org.apache.tapestry5.ioc.annotations.Symbol;
import org.apache.tapestry5.services.Dispatcher;
import org.apache.tapestry5.services.Request;
import org.apache.tapestry5.services.Response;
import org.apache.tapestry5.services.assets.AssetRequestHandler;

import com.google.common.base.Strings;

public class OfsAssetDispatcher implements Dispatcher {

	private final AssetRequestHandler _ofsHandler;
	private final String _t5AssetPathPrefix;

    public OfsAssetDispatcher(
    		@InjectService("OfsAssetRequestHandler")
    		AssetRequestHandler assetRequestHandler,
    		@Symbol(SymbolConstants.ASSET_PATH_PREFIX)
    		String t5AssetPathPrefix) {
        this._ofsHandler = assetRequestHandler;
        this._t5AssetPathPrefix = t5AssetPathPrefix;
    }

    /*
     * (non-Javadoc)
     * @see org.apache.tapestry5.services.Dispatcher#dispatch(org.apache.tapestry5.services.Request, org.apache.tapestry5.services.Response)
     */
    @Override
	public boolean dispatch(Request request, Response response) throws IOException {
        String path = request.getPath();
        
        String virtualPath = OfsFilesUtils.getVirtualPathFromUrl(path, request, _t5AssetPathPrefix);
        
        if(Strings.isNullOrEmpty(virtualPath)){
        	return false;
        }

        boolean handled = _ofsHandler.handleAssetRequest(request, response, virtualPath);
    	
        if (handled) {
            return true;
        }
        
        response.sendError(HttpServletResponse.SC_NOT_FOUND, path);

        return true;
    }

}
